<script setup lang="ts">
import MyWorker from './worker?worker&inline'
import { computed, onUnmounted, ref } from "vue"
import { compile } from "./compile"

const expr = ref('x + y = y + x')
const args = ref(compile(expr.value).args!)
const fn = computed(() => compile(expr.value))

const count = ref(0)
const fail = ref<number[]>()
const worker = ref<Worker>()

onUnmounted(finish)

function begin() {
  if (fn.value.kind == 'err') return
  count.value = 0
  args.value = fn.value.args
  fail.value = undefined

  finish()
  const w = new MyWorker
  worker.value = w
  w.postMessage([fn.value.args, fn.value.expr])
  w.onmessage = ({ data }) => {
    count.value = data.count
    if (data.type == 'fail') {
      finish()
      fail.value = data.arg
    }
  }
}

function finish() {
  worker.value?.terminate()
  worker.value = undefined
}
</script>

<template>
  表达式：<input type="text" v-model="expr">（结果为布尔值）
  <div v-if="fn.kind == 'ok'">
    随机变量：{{ fn.args.join(', ') }}<br>
    对应的 JS 代码：<code>{{ fn.expr }}</code>
  </div>
  <div v-else>
    解析错误：{{ fn.e }}
  </div>
  <hr>
  <button type="button" @click="begin" :disabled="fn.kind == 'err'">开始测试</button>
  <button type="button" @click="finish" :disabled="worker == null">停止测试</button>
  <div>
    {{ worker ? '正' : '不' }}在运行，已执行 {{ count }} 次测试。
  </div>
  <div v-if="fail != null">
    测试发现问题，参数：
    <ul>
      <li v-for="(arg, i) in fail">
        <code>{{ args[i] }} = {{ Object.is(-0, arg) ? '-0' : String(arg) }}</code>
      </li>
    </ul>
  </div>
  <div v-else>
    测试暂未发现问题
  </div>
</template>

<style scoped></style>
